<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编号" prop="equipmentNo">
        <el-input
          v-model="queryParams.equipmentNo"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间" prop="modifiedDTime">
        <el-date-picker clearable
          v-model="queryParams.modifiedDTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table 
      v-loading="loading" 
      :data="dailycheckList" 
      height="calc(100vh - 250px)"
      ref="table"
      @scroll="handleScroll"
      class="scroll-table"
    >
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="点检ID" align="center" prop="dailyCheckTaskID" />
      <el-table-column label="设备编号" align="center" prop="equipmentNo" />
      <el-table-column label="设备名称" align="center" prop="equipmentName" />
      <el-table-column label="点检结果" align="center" prop="dailyCheckResult" />
      <el-table-column label="时间" align="center" prop="modifiedDTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifiedDTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="序号" align="center" prop="sequence" />
      <el-table-column label="检点明细项" align="center" prop="checkItem" />
      <el-table-column label="方法" align="center" prop="checkMethod" />
      <el-table-column label="点检规格" align="center" prop="specification" />
      <el-table-column label="结果" align="center" prop="checkResult" />
      <template slot="empty">
        <el-empty description="暂无数据"></el-empty>
      </template>
    </el-table>

    <!-- 添加或修改设备点检对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="点检ID" prop="DailyCheckTaskID">
          <el-input v-model="form.DailyCheckTaskID" placeholder="请输入点检ID" />
        </el-form-item>
        <el-form-item label="设备编号" prop="EquipmentNo">
          <el-input v-model="form.EquipmentNo" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备名称" prop="EquipmentName">
          <el-input v-model="form.EquipmentName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="结果" prop="DailyCheckResult">
          <el-input v-model="form.DailyCheckResult" placeholder="请输入结果" />
        </el-form-item>
        <el-form-item label="时间" prop="ModifiedDTime">
          <el-date-picker clearable
            v-model="form.ModifiedDTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="序号" prop="Sequence">
          <el-input v-model="form.Sequence" placeholder="请输入序号" />
        </el-form-item>
        <el-form-item label="检点明细项" prop="CheckItem">
          <el-input v-model="form.CheckItem" placeholder="请输入检点明细项" />
        </el-form-item>
        <el-form-item label="方法" prop="CheckMethod">
          <el-input v-model="form.CheckMethod" placeholder="请输入方法" />
        </el-form-item>
        <el-form-item label="点检结果" prop="Specification">
          <el-input v-model="form.Specification" placeholder="请输入点检结果" />
        </el-form-item>
        <el-form-item label="结果" prop="CheckResult">
          <el-input v-model="form.CheckResult" placeholder="请输入结果" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDailycheck, getDailycheck, delDailycheck, addDailycheck, updateDailycheck } from "@/api/dailycheck/dailycheck";
import { parseTime } from "@/utils/ruoyi";

export default {
  name: "Dailycheck",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 设备点检表格数据
      dailycheckList: [],
      // 查询参数
      queryParams: {
        pageSize: 20,
        lastId: undefined,
        equipmentNo: null,
        equipmentName: null,
        modifiedDTime: null
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 是否正在加载更多数据
      isLoading: false,
      // 是否有更多数据
      hasMore: true
    };
  },
  watch: {
    dailycheckList: {
      handler() {
        this.$nextTick(() => {
          const tableBody = this.$refs.table.$el.querySelector('.el-table__body-wrapper');
          if (tableBody) {
            tableBody.addEventListener('scroll', this.handleScroll);
          }
        });
      },
      immediate: true
    }
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,
    /** 处理表格滚动事件 */
    handleScroll(e) {
      const target = e.target || e;
      const { scrollTop, scrollHeight, clientHeight } = target;
      
      // 当距离底部小于50px时加载更多数据
      if (scrollHeight - scrollTop - clientHeight < 50 && !this.isLoading && this.hasMore) {
        this.getList(true);
      }
    },

    /** 查询设备点检列表 */
    getList(append = false) {
      if (this.isLoading) return;
      
      this.loading = !append;
      this.isLoading = true;
      
      // 构建查询参数
      const params = {
        ...this.queryParams,
        lastId: append ? this.queryParams.lastId : undefined
      };
      
      listDailycheck(params).then(response => {
        if (response.code === 200) {
          const list = response.data.list || [];
          
          if (list.length > 0) {
            if (append) {
              this.dailycheckList = [...this.dailycheckList, ...list];
            } else {
              this.dailycheckList = list;
            }
            
            // 更新最后一条数据的ID
            this.queryParams.lastId = list[list.length - 1].ID;
            // 如果返回的数据条数小于pageSize，说明没有更多数据了
            this.hasMore = list.length >= this.queryParams.pageSize;
          } else {
            if (!append) {
              this.dailycheckList = [];
            }
            this.hasMore = false;
          }
        } else {
          this.$modal.msgError(response.msg || "获取数据失败");
          if (!append) {
            this.dailycheckList = [];
          }
          this.hasMore = false;
        }
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.$modal.msgError("获取数据失败");
        if (!append) {
          this.dailycheckList = [];
        }
        this.hasMore = false;
      }).finally(() => {
        this.loading = false;
        this.isLoading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.lastId = undefined;
      this.dailycheckList = [];
      this.hasMore = true;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageSize: 20,
        lastId: undefined,
        equipmentNo: null,
        equipmentName: null,
        modifiedDTime: null
      };
      this.hasMore = true;
      this.getList();
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dailyCheckTaskID: undefined,
        equipmentNo: undefined,
        equipmentName: undefined,
        dailyCheckResult: undefined,
        modifiedDTime: undefined,
        sequence: undefined,
        checkItem: undefined,
        checkMethod: undefined,
        specification: undefined,
        checkResult: undefined
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备点检";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDailycheck(id).then(response => {
        if (response.code === 200) {
          // 将后端返回的数据转换为表单所需的格式
          const data = response.data || {};
          this.form = {
            id: data.id,
            dailyCheckTaskID: data.dailyCheckTaskID,
            equipmentNo: data.equipmentNo,
            equipmentName: data.equipmentName,
            dailyCheckResult: data.dailyCheckResult,
            modifiedDTime: data.modifiedDTime,
            sequence: data.sequence,
            checkItem: data.checkItem,
            checkMethod: data.checkMethod,
            specification: data.specification,
            checkResult: data.checkResult
          };
          console.log('修改表单数据:', this.form); // 添加日志
          this.open = true;
          this.title = "修改设备点检";
        } else {
          this.$modal.msgError(response.msg || "获取数据失败");
        }
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.$modal.msgError("获取数据失败");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitData = {
            ...this.form,
            modifiedDTime: this.form.modifiedDTime // 确保日期格式正确
          };

          if (this.form.id != null) {
            updateDailycheck(submitData).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.$modal.msgError(response.msg || "修改失败");
              }
            }).catch(() => {
              this.$modal.msgError("修改失败");
            });
          } else {
            addDailycheck(submitData).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.$modal.msgError(response.msg || "新增失败");
              }
            }).catch(() => {
              this.$modal.msgError("新增失败");
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备点检编号为"' + ids + '"的数据项？').then(function() {
        return delDailycheck(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dailycheck/dailycheck/export', {
        ...this.queryParams,
        pageNum: undefined,
        pageSize: undefined
      }, `dailycheck_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.scroll-table {
  overflow: auto;
}
.scroll-table ::v-deep .el-table__body-wrapper {
  overflow-y: auto;
}
</style>
